// 聊天相关后端API封装

function getBaseUrl() {
  // 从webSocket地址推导http地址
  try {
    const cfg = require('@/webSocketconfig.js').default
    const ws = cfg.getWebSocketUrl()
    if (ws.startsWith('wss://')) return ws.replace('wss://', 'https://').replace('/ws', '')
    if (ws.startsWith('ws://')) return ws.replace('ws://', 'http://').replace('/ws', '')
  } catch (e) {}
  // 兜底
  return 'http://localhost:8083'
}

const BASE_URL = getBaseUrl()

export function fetchHistory(userId, otherUserId, page = 1, limit = 50) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}/api/chat/history/${encodeURIComponent(userId)}/${encodeURIComponent(otherUserId)}`,
      method: 'GET',
      data: { page, limit },
      success: (res) => resolve(res.data || []),
      fail: reject
    })
  })
}

export function fetchRecent(userId, limit = 50) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}/api/chat/recent/${encodeURIComponent(userId)}`,
      method: 'GET',
      data: { limit },
      success: (res) => resolve(res.data || []),
      fail: reject
    })
  })
}

export function clearUnread(userId, otherUserId) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}/api/chat/unread/clear`,
      method: 'POST',
      data: { userId, otherUserId },
      success: (res) => resolve(res.data || { success: true }),
      fail: reject
    })
  })
}